#include "FiveWin.ch"

static oLastItem

//----------------------------------------------------------------------------//

CLASS TMenu

   DATA   hMenu
   DATA   aItems

   METHOD New() CONSTRUCTOR
   METHOD Add( oMenuItem )
   METHOD Command( nCommand )
   METHOD LastItem() BLOCK { || oLastItem }
   METHOD GetMenuItem( nItemId ) BLOCK ;
                           { | Self, nItemId | SearchItem( ::aItems, nItemId ) }

ENDCLASS

//----------------------------------------------------------------------------//

METHOD New() CLASS TMenu

   ::hMenu  = CreateMenu()
   ::aItems = {}

return

//----------------------------------------------------------------------------//

METHOD Add( oMenuItem ) CLASS TMenu

   AAdd( ::aItems, oMenuItem )

   if oMenuItem:bAction:ClassName() == "TMENU"
      AppendMenu( ::hMenu, MF_POPUP, oMenuItem:bAction:hMenu,;
                  oMenuItem:cPrompt )
   else
      if oMenuItem:cPrompt != nil
         AppendMenu( ::hMenu, MF_ENABLED, oMenuItem:nId,;
                     oMenuItem:cPrompt )
      else
         AppendMenu( ::hMenu, MF_SEPARATOR, oMenuItem:nId, "" )
      endif
   endif

return

//----------------------------------------------------------------------------//

METHOD Command( nCommand ) CLASS TMenu

   local oMenuItem := ::GetMenuItem( nCommand )

   if oMenuItem:bAction != nil
      oLastItem = oMenuItem
      Eval( oMenuItem:bAction )
   endif

return

//----------------------------------------------------------------------------//

static function SearchItem( aItems, nId )

   local n      := 1
   local lFound := .f.
   local oReturn

   while n <= Len( aItems ) .and. ! lFound
      if aItems[ n ]:nId == nId
         return aItems[ n ]
      else
         if aItems[ n ]:bAction:ClassName() == "TMENU"
            if aItems[ n ]:bAction:hMenu == nId
               return nil
            else
               oReturn = SearchItem( aItems[ n ]:bAction:aItems, nId )
               if oReturn != nil
                  exit
               endif
            endif
         endif
      endif
      n++
   end

return oReturn

//----------------------------------------------------------------------------//
